from Config.BLPConnConfig import *
import zmq
import json
from StringIO import StringIO


def query_blp_data(securities, fields, start_date=None, end_date=None):
	context = zmq.Context()
	socket = context.socket(zmq.REQ)
	socket.setsockopt(zmq.LINGER, 0)
	socket.connect(BLP_CONN_STR)
	
	request = format_request_json_param(securities, fields, start_date, end_date)
	socket.send(request)
	
	poller = zmq.Poller()
	poller.register(socket, zmq.POLLIN)
	if not poller.poll(RECV_TIMEOUT*1000):
		print 'warn, timeout'
		socket.close()
		return {}
	else:	
		#print 'send complete...'
		response = socket.recv()
		stream_reader = StringIO(response)
		return json.load(stream_reader)

	
def format_request_json_param(securities, fields, start_date, end_date):
	tmp = {}
	tmp["securities"] = securities
	tmp["fields"] = fields
	if start_date and end_date:
		tmp["startDate"] = start_date.strftime('%Y%m%d')
		tmp["endDate"] = end_date.strftime('%Y%m%d')
	
	return json.dumps(tmp)

	
	